package com.ragdollcat.thirdaicodegenerate.util;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class IpUtils {

    /**
     * 获取当前请求的 IP 地址（处理代理场景）
     */
    public static String getCurrentIp() {
        // 1. 获取当前请求上下文
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return "unknown"; // 非 Web 环境或无请求上下文
        }

        // 2. 获取 HttpServletRequest 对象
        HttpServletRequest request = requestAttributes.getRequest();
        if (request == null) {
            return "unknown";
        }

        // 3. 处理代理场景的 IP 转发（优先取 X-Forwarded-For 等头信息）
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }

        // 4. 若以上代理头均不存在，直接取远程地址
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 5. 处理多代理情况（X-Forwarded-For 可能包含多个 IP，取第一个）
        if (ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }

        return ip;
    }
}